var ONETRUST_KEY = '';
var ONETRUST_PROD_URL = '';
var PENDO_KEY = '';
var PENDO_INTEGRATION_KEY = '';

    initializeKeys = function(oneTrustKey, oneTrustURL, pendoKey, pendoIntKey){
        ONETRUST_KEY = oneTrustKey;
        ONETRUST_PROD_URL = oneTrustURL;
        PENDO_KEY = pendoKey;
        PENDO_INTEGRATION_KEY = pendoIntKey;
      };
	
      PENDO_SERVICE = function() {
    	    return {
    	        initializePendoConfig: function() {
    	            const script = document.createElement('script');
    	            script.setAttribute('type', 'text/javascript');
    	            script.setAttribute('class', 'optanon-category-C0003');

    	            script.text = `
    	            (function(apiKey) {
    	              (function(p, e, n, d, o) { 
    	                let v, w, x, y, z; 
    	                o = p[d] = p[d] || {}; 
    	                o._q = [];
    	                v = ['initialize', 'identify', 'updateOptions', 'pageLoad', 'track']; 
    	                for (w = 0, x = v.length; w < x; ++w)(function(m) {
    	                  o[m] = o[m] || function() {o._q[m === v[0] ? 'unshift' : 'push']([m].concat([].slice.call(arguments, 0))); }; 
    	                })(v[w]);
    	                y = e.createElement(n); 
    	                y.async = !0; 
    	                y.src = 'https://cdn.pendo.io/agent/static/' + apiKey + '/pendo.js';
    	                z = e.getElementsByTagName(n)[0]; 
    	                z.parentNode.insertBefore(y, z); 
    	              })(window, document, 'script', 'pendo');
    	            })('${PENDO_KEY}');
    	        `;

    	            const headerEl = document.getElementsByTagName('head')[0];
    	            if (headerEl) {
    	                headerEl.appendChild(script);
    	            }
    	        },

    	        /* make sure to invoke initializePendoMetadata() method before initializeOT()
    	        to ensure that OptanonWrapper() method is placed in a script under <head> element before One Trust scripts*/
    	        initializePendoMetadata: function(pendoDetails) {
    	            localStorage.setItem('pendoDetails', JSON.stringify(pendoDetails))

    	            const script = document.createElement('script');
    	            script.setAttribute('type', 'text/javascript');


    	            script.text = `
    	                function OptanonWrapper() {
    	                    /* dataLayer is the one which gets updated with the latest categories whenever
    	                    we make any changes to the cookie categories from OneTrust preference center */
    	                    var dataLayer = window.dataLayer;
    	                    var GroupsArr = dataLayer.filter((item)=> item.event === 'OneTrustGroupsUpdated');
    	    
    	                    /* pendoDetails is an item which provides metadata required for initializing Pendo. this is JCR product specific */
    	                    var user = (JSON.parse(localStorage.getItem('pendoDetails')) || {}).visitor || {};
    	    
    	                    /* For pre login, the anonymous id generated by Pendo can be used as the visitorId
    	                    For post login, this visitorId can be the same used as visitorId in pendo.initialize() method */
    	                    const visitorId = user.id ? user.id : window.pendo.get_visitor_id();
    	                    if (GroupsArr.length > 1) { 
    	                        /* to find which categories were updated from OneTrust Banner after first opt-in or opt-out */
    	                        const previousCategoriesList = GroupsArr[GroupsArr.length-2]['OnetrustActiveGroups'].split(',');
    	                        const updatedCategoriesList = GroupsArr[GroupsArr.length-1]['OnetrustActiveGroups'].split(',');
    	                        let FunctionalCategoryChanged = false;
    	                        let TargetingCategoryChanged = false;
    	                        
    	                        if (previousCategoriesList.indexOf('C0003') !== -1 && updatedCategoriesList.indexOf('C0003') === -1) {
    	                            FunctionalCategoryChanged = true;
    	                            dnpValue = true;
    	                        } else if (previousCategoriesList.indexOf('C0003') === -1 && updatedCategoriesList.indexOf('C0003') !== -1) {
    	                            FunctionalCategoryChanged = true;
    	                            dnpValue = false;
    	                        } else {
    	                            FunctionalCategoryChanged = false;
    	                        }
    	    
    	                        if (previousCategoriesList.indexOf('C0004') !== -1 && updatedCategoriesList.indexOf('C0004') === -1) {
    	                            TargetingCategoryChanged = true;
    	                            targetingCookieValue = 'NO';
    	                        } else if (previousCategoriesList.indexOf('C0004') === -1 && updatedCategoriesList.indexOf('C0004') !== -1) {
    	                            TargetingCategoryChanged = true;
    	                            targetingCookieValue = 'YES';
    	                        } else {
    	                            TargetingCategoryChanged = false;
    	                        }
    	                        
    	                        if (FunctionalCategoryChanged) {
    	                            callDNP(visitorId, dnpValue);                        
    	                        }
    	                        if (TargetingCategoryChanged) {
    	                            /* this timeout is added because Pendo allows only one API call per second per visitor */
    	                            setTimeout(() => {
    	                                updateCustomMetadataField(visitorId, targetingCookieValue)
    	                            }, 2000);
    	                        }
    	    
    	                    } else if (GroupsArr.length === 1) {
    	                        const updatedCategoriesList = GroupsArr[GroupsArr.length-1]['OnetrustActiveGroups'].split(',');
    	                        const dnpValue = updatedCategoriesList.indexOf('C0003') === -1;
    	                        const targetingCookieValue = updatedCategoriesList.indexOf('C0004') === -1 ? 'NO' : 'YES';
    	    
    	                        /* createVisitorId() is invoked for the first time to make sure that the visitor exists in Pendo to
    	                        further invoke callDNP() or updateCustomMetadataField(). If the visitor is not existing
    	                        then these 2 API calls will fail with a 404 visitor not found */
    	                        createVisitorId(user, visitorId, dnpValue, targetingCookieValue);
    	                    }
    	                }
    	    
    	                function createVisitorId(user, visitorId, dnpValue, targetingCookieValue) {
    	                    const headers = requestHeaders();

    	                    //const request = new Request('/scholaroneAJAXServlet?AJAX_TAG_ACTION=AJAX_MAKE_PENDO_CALL&PENDO_CALL_METHOD=POST&PENDO_CALL=metadata/visitor/agent/value?create=true', {
    	                    //    method: 'POST',
    	                    //    headers,
                            //    body: JSON.stringify([{
    	                    //        visitorId,
    	                    //        values: {
    	                    //            firstname: user.firstName,
    	                    //            lastname: user.lastName
    	                    //        }
    	                    //    }])
    	                    //});

    	                    const request = new Request('https://app.pendo.io/api/v1/metadata/visitor/agent/value?create=true', {
    	                        method: 'POST',
    	                        headers,
    	                        body: JSON.stringify([{
    	                            visitorId,
    	                            values: {
    	                                firstname: user.firstName,
    	                                lastname: user.lastName
    	                            }
    	                        }])
    	                    });
    	                    
    	                    fetch(request)
    	                        .then(async response => {
    	                            if (response.status === 200) {
    	                                callDNP(visitorId, dnpValue);
    	                                /* this timeout is added because Pendo allows only one API call per second per visitor */
    	                                setTimeout(() => {
    	                                    updateCustomMetadataField(visitorId, targetingCookieValue)
    	                                }, 2000);
    	                            }
    	                        })
    	                        .catch(error => {
    	                            console.error('There was an error!', error);
    	                        });
    	                }
    	    
    	                function callDNP(visitorId, dnpValue) {
    	                    const headers = requestHeaders();
    	                    //const request = new Request('/scholaroneAJAXServlet?AJAX_TAG_ACTION=AJAX_MAKE_PENDO_CALL&PENDO_CALL_METHOD=PUT&PENDO_CALL=metadata/visitor/pendo/value/' + visitorId + '/donotprocess', {
    	                    //    method: 'POST',
    	                    //    headers,
    	                    //    body: JSON.stringify(dnpValue)
    	                    //});

    	                    const request = new Request('https://app.pendo.io/api/v1/metadata/visitor/pendo/value/' + visitorId + '/donotprocess', {
                                method: 'PUT',
                                headers,
                                body: JSON.stringify(dnpValue)
                            });
    	    
    	                    fetch(request)
    	                        .then(async response => {
    	                            if (!dnpValue) {
    	                                initializePendo();
    	                            }
    	                        })
    	                        .catch(error => {
    	                            console.error('There was an error!', error);
    	                        });
    	                }
    	    
    	                function initializePendo() {
    	                    var pendoDetails = JSON.parse(localStorage.getItem('pendoDetails')) || {};
    	                    window.pendo.initialize(pendoDetails);
    	                }
    	    
    	                function updateCustomMetadataField(visitorId, targetingCookieValue) {
    	                    const headers = requestHeaders();

                            //const request = new Request('/scholaroneAJAXServlet?AJAX_TAG_ACTION=AJAX_MAKE_PENDO_CALL&PENDO_CALL_METHOD=PUT&PENDO_CALL=metadata/visitor/custom/value/' + visitorId + '/targetingcookies', {
    	                    //    method: 'POST',
    	                    //    headers,
                            //   body: JSON.stringify(targetingCookieValue)
    	                    //});

    	                    const request = new Request('https://app.pendo.io/api/v1/metadata/visitor/custom/value/' + visitorId + '/targetingcookies', {
    	                        method: 'PUT',
    	                        headers,
    	                        body: JSON.stringify(targetingCookieValue)
    	                    });
    	    
    	                    fetch(request)
    	                        .then(async response => {
    	                        })
    	                        .catch(error => {
    	                            console.error('There was an error!', error);
    	                        });
    	                }
    	    
    	                function requestHeaders() {
    	                    const headers = new Headers();
    	                    headers.append('Content-Type', 'application/json');
    	                    headers.append('x-pendo-integration-key', '${PENDO_INTEGRATION_KEY}');
    	                    return headers;
    	                }
    	            `;
    	            const headerEl = document.getElementsByTagName('head')[0];
    	            if (headerEl) {
    	                headerEl.appendChild(script);
    	            }
    	        },

    	        getApplicableKey: function(oneTrustKey, productionURL) {
    	            let key = oneTrustKey;

    	            if (!productionURL || document.location.href.indexOf(productionURL) < 0) {
    	                key += '-test';
    	            }

    	            return key;
    	        },

    	        initializeOT: function () {
    	            const cookieBannerId = this.getApplicableKey(ONETRUST_KEY, ONETRUST_PROD_URL);
    	            // JS: Remove this .. new CookePro banner is being used. Not sure what it did, new one seems to call it from otSDKStub.js
    	            //const script1 = document.createElement('script');
    	            //script1.setAttribute('type', 'text/javascript');
    	            //script1.setAttribute('src', `https://cookie-cdn.cookiepro.com/consent/${cookieBannerId}/OtAutoBlock.js`);

    	            const script2 = document.createElement('script');
    	            script2.setAttribute('type', 'text/javascript');
    	            script2.setAttribute('src', 'https://cookie-cdn.cookiepro.com/scripttemplates/otSDKStub.js');
    	            script2.setAttribute('charset', 'UTF-8');
    	            script2.setAttribute('data-domain-script', cookieBannerId);

    	            const header = document.getElementsByTagName('head')[0];
    	            if (header) {
    	                //header.appendChild(script1);
    	                header.appendChild(script2);
    	            }
    	        },

    	        openCookiesPreferences: function() {
    	            if (typeof OneTrust !== 'undefined') {
    	                OneTrust.ToggleInfoDisplay();
    	            } else {
    	                throw new Error('Library OneTrust is not loaded');
    	            }
    	        }
    	    }
    	}();